package nero.yncc.com.createart.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.adapter.AdapteChangjingDetailList;
import nero.yncc.com.createart.adapter.AdapterDetailChangjing;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.BeanGoodChangjing;
import nero.yncc.com.createart.bean.ChangjingBean;
import nero.yncc.com.createart.bean.GodBean;
import nero.yncc.com.createart.custom.IconView;
import nero.yncc.com.createart.custom.MyRecyclerView;
import nero.yncc.com.createart.custom.MyViewPager;
import nero.yncc.com.createart.custom.PullUpToLoadMore;
import nero.yncc.com.createart.custom.PullUpToLoadMoreAutoTop;
import nero.yncc.com.createart.fragment.FragmentPicBIg;
import nero.yncc.com.createart.fragment.FragmentChangjingSmallPic;
import nero.yncc.com.createart.utils.ArrayUtils;
import nero.yncc.com.createart.utils.HttpUtils;
import nero.yncc.com.createart.utils.PopGuigeChangjing;
import nero.yncc.com.createart.utils.TextUtil;

import static android.view.View.GONE;

/**
 * Created by nero on 2017/6/26.
 */

@ContentView(R.layout.activity_changjing_detail)
public class ActivityChangjingDetail extends BaseActivity {
    @ViewInject(R.id.vp_main)
    ViewPager vp_main;
    @ViewInject(R.id.ll_dom)
    LinearLayout ll_dom;
    @ViewInject(R.id.rl_dom)
    RelativeLayout rl_dom;

    @ViewInject(R.id.rc_changjing)
    GridView rc_changjing;
    @ViewInject(R.id.tv_big_content)
    TextView tv_big_content;

    @ViewInject(R.id.rc_list)
    MyRecyclerView rc_list;

    @ViewInject(R.id.rl_big)
    RelativeLayout rl_big;
    @ViewInject(R.id.ll_dom_big)
    LinearLayout ll_dom_big;
    @ViewInject(R.id.rl_dom_big)
    RelativeLayout rl_dom_big;
    @ViewInject(R.id.vp_main_big)
    ViewPager vp_main_big;
    @ViewInject(R.id.icon_big_collection)
    IconView icon_big_collection;
    @ViewInject(R.id.icon_big_detail)
    IconView icon_big_detail;
    @ViewInject(R.id.tv_big_style)
    TextView tv_big_style;
    @ViewInject(R.id.tv_allNUm)
    TextView tv_allNUm;
    @ViewInject(R.id.tv_title)
    TextView tv_title;
    @ViewInject(R.id.tv_attr)
    TextView tv_attr;
    @ViewInject(R.id.tv_content)
    TextView tv_content;
    @ViewInject(R.id.tv_sheng_all)
    TextView tv_sheng_all;
    @ViewInject(R.id.tv_price_all)
    TextView tv_price_all;
    @ViewInject(R.id.tv_all_num)
    TextView tv_all_num_end;
    @ViewInject(R.id.sc_top)
    ScrollView sc_top;
    @ViewInject(R.id.sr_bottom)
    ScrollView sr_bottom;
    @ViewInject(R.id.ptlm)
    PullUpToLoadMoreAutoTop ptlm;
    @ViewInject(R.id.icon_back_big)
    IconView icon_back_big;
    @ViewInject(R.id.icon_back_small)
    IconView icon_back_small;
    @ViewInject(R.id.ll_shop)
    LinearLayout ll_shop;
    @ViewInject(R.id.tv_mores)
    TextView tv_mores;
    @ViewInject(R.id.btn_addShopCar)
    Button btn_addShopCar;

    View view_red;
    View view_red_big;

    AdapterDetailChangjing adapter_changjing;
    ArrayList<ChangjingBean.ChangjingInBean> arrayList_changjing; //展示在中间的场景类型
    AdapteChangjingDetailList adapter_changjinggoods;
    ArrayList<BeanGoodChangjing> arrayList_god;

    int page = 5;//幻灯图片总共的页数

    ChangjingBean changjingBean; //传递来的场景Bean
    HashMap<String, BeanGoodChangjing> hashMap_goodALl;  //存放所有的商品 key是商品ID
    HashMap<String, ArrayList<BeanGoodChangjing>> hashMap_good_changjing;  //存放场景所有商品 key是场景ID

    @Override
    protected void initView() {
        super.initView();
    }


    @Override
    protected void initData() {
        super.initData();
        arrayList_hadChoose=new ArrayList<>();
        //初始化传递来的bean
        hashMap_goodALl = new HashMap<>();
        hashMap_good_changjing = new HashMap<>();
        changjingBean = (ChangjingBean) getIntent().getSerializableExtra("data");  //传递来的场景Bean
        arrayList_changjing = (ArrayList<ChangjingBean.ChangjingInBean>) changjingBean.getCategory_list();
        page = arrayList_changjing.size();    //幻灯图片总共的页数
        tv_allNUm.setText("共" + arrayList_changjing.size() + "个场景");
        tv_title.setText(TextUtil.getText(changjingBean.getName(), "暂无标题"));
        tv_attr.setText(changjingBean.getHuxing_name() + "  " + changjingBean.getFengge_name() + "  " + changjingBean.getMianji() + "m²");
        tv_content.setText(TextUtil.getText(changjingBean.getCategory_list().get(0).getDescription(), "暂无简介"));
        tv_big_style.setText(TextUtil.getText(changjingBean.getFengge_name(), "") + "  " + arrayList_changjing.get(0).getName());
        tv_big_content.setText(TextUtil.getText(arrayList_changjing.get(0).getDescription(), "该场景暂无简介"));


        //一排场景的名字按钮
        arrayList_changjing.get(0).setChoose(true);
        adapter_changjing = new AdapterDetailChangjing(mContext, arrayList_changjing, new AdapterDetailChangjing.ChildClick() {
            @Override
            public void click(int position) {
                if (position > page - 1) {
                    showToast("该场景没有上传图片");
                } else {
                    setChangjingClick(position);
                }
                String id = arrayList_changjing.get(position).getId();//判断内存是否有当前ID的商品数组 没有才请求网络
                if (hashMap_good_changjing.get(id) == null) {
                    getData(id);
                } else {
                    ArrayUtils.copy(hashMap_good_changjing.get(id), arrayList_god, true);
                    adapter_changjinggoods.notifyDataSetChanged();
                }

            }
        });

        rc_changjing.setAdapter(adapter_changjing);
        adapter_changjing.notifyDataSetChanged();
//        setListViewHeight();
//场景商品详情

        arrayList_god = new ArrayList<>();
        adapter_changjinggoods = new AdapteChangjingDetailList(mContext, arrayList_god, hashMap_goodALl);
//        pl_good.setNestedScrollingEnabled(false);
        rc_list.setAdapter(adapter_changjinggoods);

        initViewPager();
        initViewPagerBIg();
    }

    @Override
    protected void getHttpData() {
        super.getHttpData();
        getData(arrayList_changjing.get(0).getId());
    }
    PopGuigeChangjing popGuigeChangjing;
    /**
     * 获取商品列表
     *
     * @param placeId 场景位置ID
     */
    protected void getData(final String placeId) {
        super.getData();
        final HashMap<String, String> hashMap = new HashMap<>();

        hashMap.put("id", changjingBean.getId());
        hashMap.put("category_id", placeId);
        new HttpUtils().post(this, Constants.API_CHANGJING_GOODS, hashMap, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                try {
                    JSONArray jsonArray = (JSONArray) json;
                    ArrayList<BeanGoodChangjing> arrayList_caches = new ArrayList();
                    arrayList_god.clear();
                    adapter_changjinggoods.notifyDataSetChanged();
                    for (int a = 0; a < jsonArray.length(); a++) {
                        BeanGoodChangjing bean = JSON.parseObject(jsonArray.getString(a), BeanGoodChangjing.class);
                        arrayList_god.add(bean);
                        arrayList_caches.add(bean);
                        if (hashMap_goodALl.get(bean.getGoods().getGoods_id()) == null)
                            hashMap_goodALl.put(bean.getGoods().getGoods_id(), bean);
                    }
                    hashMap_good_changjing.put(placeId, arrayList_caches);
                    adapter_changjinggoods.notifyDataSetChanged();
                    rc_list.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
//                    setListViewHeightBasedOnChildren(rc_list);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String failMsg) {

            }
        });

    }

    @Override
    protected void initListener() {
        super.initListener();
        icon_big_collection.setOnClickListener(this);
        icon_big_detail.setOnClickListener(this);
        icon_back_big.setOnClickListener(this);
        icon_back_small.setOnClickListener(this);
        ptlm.setOnScrollListener(new PullUpToLoadMoreAutoTop.OnMyScrollListner() {
            @Override
            public void Scroll(int state) {
                switch (state) {
                    case PullUpToLoadMoreAutoTop.STATE_TOP:
                        ll_shop.setVisibility(GONE);
                        break;
                    case PullUpToLoadMoreAutoTop.STATE_BOTTOM:
                        ll_shop.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });
        tv_mores.measure(0, 0);
        ptlm.setCut(tv_mores.getMeasuredHeight());
        btn_addShopCar.setOnClickListener(this);
    }

    @Override
    protected void doClick(int id) {
        super.doClick(id);
        switch (id) {
            case R.id.icon_big_detail:
//                rl_big.setVisibility(View.GONE);
//                sc_top.scrollTo(0,5000);
                ptlm.scrollNext(screenHeight);
                break;
            case R.id.icon_back_big:
                finish();
                break;
            case R.id.icon_back_small:
                ptlm.scrollFirst();
                break;
            case R.id.btn_addShopCar:
                //获取选中的商品
                if (arrayList_hadChoose.size() == 0) {
                    showToast("请先选择商品");
                    return;
                }
                popGuigeChangjing = new PopGuigeChangjing(mContext, arrayList_hadChoose, userBean,changjingBean.getId());
                popGuigeChangjing.show(this);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(popGuigeChangjing!=null && popGuigeChangjing.isShow()){
                popGuigeChangjing.disMiss();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化大图的viewPager
     */
    private void initViewPagerBIg() {
        setStateBarColor(R.color.black);
        if (page > 1) {
            for (int a = 0; a < page; a++) {
                View views = LinearLayout.inflate(mContext, R.layout.view_dom_gray, null);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
                params.setMargins(5, 5, 5, 5);
                views.setLayoutParams(params);
                ll_dom_big.addView(views);
            }

            view_red_big = LinearLayout.inflate(mContext, R.layout.view_dom_gray, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(15, 15);
            params.setMargins(5, 5, 5, 5);
            view_red_big.setLayoutParams(params);
            view_red_big.setBackgroundResource(R.color.white);
            params.addRule(RelativeLayout.ALIGN_LEFT, R.id.ll_dom_big);
            rl_dom_big.addView(view_red_big);
            rl_big.setLayoutParams(new LinearLayout.LayoutParams(-1, screenHeight));
            vp_main_big.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view_red_big.getLayoutParams();
                    //70为一个

                    params.setMargins((int) (25 * (positionOffset) + 25 * position) + 5, 5, 5, 5);
                    view_red_big.setLayoutParams(params);
                    view_red_big.setBackgroundResource(R.drawable.yuan_gray_white);
                }

                @Override
                public void onPageSelected(int position) {
                    tv_big_style.setText(TextUtil.getText(changjingBean.getFengge_name(), "") + "  " + arrayList_changjing.get(position).getName());
                    tv_big_content.setText(TextUtil.getText(arrayList_changjing.get(position).getDescription(), "该场景暂无简介"));
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }
        vp_main_big.setAdapter(new FragmentPagerAdapter(this.getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                FragmentPicBIg fragmentPicBIg = new FragmentPicBIg();
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", changjingBean.getCategory_list().get(position));
                fragmentPicBIg.setArguments(bundle);
                return fragmentPicBIg;
            }

            @Override
            public int getCount() {
                return page;
            }
        });
    }

    /**
     * 初始化小图的Viewpager
     */
    private void initViewPager() {
        if (page > 1) {
            for (int a = 0; a < page; a++) {
                View views = LinearLayout.inflate(mContext, R.layout.view_dom_white, null);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
                params.setMargins(5, 5, 5, 5);
                views.setLayoutParams(params);
                ll_dom.addView(views);
            }

            view_red = LinearLayout.inflate(mContext, R.layout.view_dom, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(15, 15);
            params.setMargins(5, 5, 5, 5);
            view_red.setLayoutParams(params);
            view_red.setBackgroundResource(R.drawable.tv_dom);
            params.addRule(RelativeLayout.ALIGN_LEFT, R.id.ll_dom);
            rl_dom.addView(view_red);

            vp_main.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view_red.getLayoutParams();
                    //70为一个

                    params.setMargins((int) (25 * (positionOffset) + 25 * position) + 5, 5, 5, 5);
                    view_red.setLayoutParams(params);
                    view_red.setBackgroundResource(R.drawable.tv_dom_yellow);
                }

                @Override
                public void onPageSelected(int position) {
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }
//        vp_main.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                rl_big.setVisibility(View.VISIBLE);
//                return false;
//            }
//        });
        vp_main.setAdapter(new FragmentPagerAdapter(this.getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                FragmentChangjingSmallPic fragmentPicChangjing = new FragmentChangjingSmallPic();
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", changjingBean.getCategory_list().get(position));
                fragmentPicChangjing.setArguments(bundle);
                return fragmentPicChangjing;
            }

            @Override
            public int getCount() {
                return page;
            }
        });
    }


    private void setChangjingClick(int position) {
        for (ChangjingBean.ChangjingInBean bean : arrayList_changjing) {
            bean.setChoose(false);
        }
        arrayList_changjing.get(position).setChoose(true);
        vp_main.setCurrentItem(position);
        adapter_changjing.notifyDataSetChanged();
    }

    public void setListViewHeightBasedOnChildren(ListView lv) {
        if (lv == null) {
            return;
        }
        ListAdapter adapter = lv.getAdapter();
        if (adapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i, null, lv);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = lv.getLayoutParams();
        params.height = totalHeight + (lv.getDividerHeight() * (lv.getCount() - 1));//这里还将分割线的高度考虑进去了，统计出所有分割线占有的高度和
        lv.setLayoutParams(params);
    }


    int goodsChooseNUm = 0;
    double goodsChoosePrice = 0;
    double goodsShengPrice = 0;

    ArrayList<BeanGoodChangjing> arrayList_hadChoose;

    public void setGoodsPriceAndNum() {
        arrayList_hadChoose.clear();
        goodsChooseNUm = 0;
        goodsChoosePrice = 0;
        goodsShengPrice = 0;
        Set<String> set = hashMap_goodALl.keySet();
        for (String s : set) {
            BeanGoodChangjing bean_cache = hashMap_goodALl.get(s);
            if (bean_cache.isChoose()) {
                arrayList_hadChoose.add(bean_cache);
                goodsChooseNUm += bean_cache.getNum();
                try {
                    goodsChoosePrice += Double.parseDouble(bean_cache.getGoods().getShop_price()) * bean_cache.getNum();
                    goodsShengPrice += Double.parseDouble(bean_cache.getGoods().getMarket_price()) * bean_cache.getNum();
                } catch (Exception e) {

                }
            }
        }

        if (goodsChooseNUm > 0) {
            tv_all_num_end.setVisibility(View.VISIBLE);
            tv_sheng_all.setVisibility(View.VISIBLE);
        } else {
            tv_all_num_end.setVisibility(GONE);
            tv_sheng_all.setVisibility(GONE);
        }
        showLog(goodsChooseNUm + "");
        tv_all_num_end.setText(goodsChooseNUm + "件商品");
        tv_sheng_all.setText("立省￥" + (goodsShengPrice - goodsChoosePrice));
        tv_price_all.setText("￥" + goodsChoosePrice);
    }

    static final String COLLECTION_STATE_GET = "GET_COLLECT_STATE", COLLECTION_STATE_SET = "DO_COLLECT", COLLECTION_STATE_CANCLE = "CANCEL_COLLECT";

    private void collection(final String action) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", changjingBean.getId());
        hashMap.put("user_id", userBean.getUser_id());
        hashMap.put("action", action);
        new HttpUtils().post(this, Constants.API_COLLECTION_CHANGJING, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                showToast(msg);
                if (action.equals("GET_COLLECT_STATE")) {

                }
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
            }
        });

    }

}
